<template>
	<div>
		<div class="flex items-center py-1 px-2 rounded hover:bg-gray-200 cursor-pointer transition-colors"
			@click="toggleExpanded" @contextmenu.prevent="showContextMenu">
			<i :class="[
				node.isDirectory ? (expanded ? 'fa fa-folder-open-o' : 'fa fa-folder-o') : 'fa fa-file-text-o',
				'mr-2 text-gray-600'
			]"></i>
			<span class="truncate">{{ node.name }}</span>
			<i v-if="node.isDirectory"
				:class="[expanded ? 'fa fa-chevron-down' : 'fa fa-chevron-right', 'ml-auto text-xs']"></i>
		</div>
		<div v-if="expanded && node.children" class="pl-4 mt-1 space-y-1">
			<FileNode v-for="child in node.children" :key="child.path" :node="child" @navigate="navigateToFile"
				@show-context-menu="showContextMenuInParent" />
		</div>
	</div>
</template>

<script setup>

const props = defineProps({
	node: {
		type: Object,
		required: true
	}
})

const emits = defineEmits(['navigate', 'show-context-menu'])

const expanded = ref(false)

const toggleExpanded = () => {
	if (props.node.children) {
		expanded.value = !expanded.value
	} else {
		emits('navigate', props.node.path)
	}
}

const navigateToFile = (path) => {
	emits('navigate', path)
}

// 新增：显示右键菜单
const showContextMenu = (event) => {
	emits('show-context-menu', {
		x: event.clientX,
		y: event.clientY,
		node: props.node
	})
}

// 新增：处理子节点的右键菜单事件
const showContextMenuInParent = (event) => {
	emits('show-context-menu', event)
}

onMounted(() => {
	if (props.node.path === '.') {
		expanded.value = true
	}
})
</script>